<?php

namespace Drupal\shusy_category\Entity;

use Drupal\shusy_category\ViewsController\Traits\ShusyCategoryStatusTrait;
use Entity;

class ShusyCategory extends Entity {

  public $id;

  public $vid;

  public $uid;

  public $op_uid;

  public $created;

  public $changed;

  public $is_new_revision;

  public $name;

  public $icon;

  public $period = 0;

  public $parent_top = 0;

  public $parent = 0;

  public $weight = 0;

  public $depth = 0;

  public $status = 0;

  public $depth_1 = 0;

  public $depth_2 = 0;

  public $depth_3 = 0;

  use ShusyCategoryStatusTrait;

  function __construct($values = []) {
    $this->is_new_revision = TRUE;
    parent::__construct($values, 'shusy_category');
  }

  public function save() {
    $this->changed = REQUEST_TIME;
    if (empty($this->created)) {
      $this->created = REQUEST_TIME;
    }

    $this->op_uid = $GLOBALS['user']->uid;
    if (empty($this->uid)) {
      $this->uid = $GLOBALS['user']->uid;
    }
    $parent = shusy_category_load($this->parent);
    if ($parent instanceof ShusyCategory) {
      $this->parent_top = $parent->parent;
    }
    //计算冗余数据
    switch ($this->depth) {
      case 0:
        $this->depth_3 = 0;
        $this->depth_2 = 0;
        $this->depth_1 = $this->id;
        break;
      case 1:
        $this->depth_3 = 0;
        $this->depth_2 = $this->id;
        $this->depth_1 = $this->parent;
        break;
      case 2:
        $this->depth_3 = $this->id;
        $this->depth_2 = $this->parent;
        $this->depth_1 = $this->parent_top;
        break;
    }
    return parent::save();
  }

  function icon() {
    if ($this->icon > 0) {
      return $this->icon;
    }
    $default = variable_get_value('shusy_category:default');
    return $default;
  }
}
